<?php
namespace common\logic;
use common\models\AdvertModel;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;
class AdvertLogic extends Logic
{
	/**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return AdvertModel::find();
    }
    

	
	public function getPcAdv($atype)
    {
    	//$pcAdv = 
    	$query = AdvertModel::find();//$this->getQuery(['atype' => $atype,'isshow'=>1],[],[])
		$query->joinWith(['house']);
		$query->select("ph_house.house_name,ph_house.address,ph_house.house_unit_price,ph_advert.*");
		$query->andWhere(['atype' => $atype,'isshow'=>1]);
		$query->orderBy(['ph_advert.id'=>SORT_DESC]);
		$pcAdv = $query->limit(6)->asArray()->all();
		
		
		
        return ['pcadv'=>$pcAdv];
    }
	
	//按照类型获得广告数量
	public function getPcAdvNum($atype)
    {
    	$pcAdv = $this->getQuery(['atype' => $atype,'isshow'=>1])->all();
        return count($pcAdv);
    }
	
	public function AdvertSave(AdvertModel $model){
		
		//advicon 字段
		$this->saveFile($model, 'advicon');
        $rs = $model->save();
        return $rs;
	}
	
	/**
     * 保存上传文件banner、广告位
     *
     * @param \common\models\HouseModel $model
     * @param                           $key
     */
    protected function saveFile(AdvertModel $model, $key)
    {
        if ($_FILES && !empty($_FILES['AdvertModel']['name'][$key])) {
            $filePath = "/upload/$key/";
            $fileName = $filePath . uniqid() . '.' . pathinfo($_FILES['AdvertModel']['name'][$key], PATHINFO_EXTENSION);
            $filePath = \Yii::getAlias('@webroot') . $filePath;
            if (!file_exists($filePath)) {
                mkdir($filePath, 0777, true);
            }
            $savePath = \Yii::getAlias('@webroot') . $fileName;
            if (move_uploaded_file($_FILES['AdvertModel']['tmp_name'][$key], $savePath)) {
                $model->$key = $fileName;
            }
        }
    }
}
?>